package servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import modle.Room;
import modle.Stadium;
import modle.StadiumDAO;

import com.google.gson.Gson;



public class GetRoomsServlet extends HttpServlet {

	/**
	 * The doGet method of the servlet. <br>
	 *
	 * This method is called when a form has its tag value method equals to get.
	 * 
	 * @param request the request send by the client to the server
	 * @param response the response send by the server to the client
	 * @throws ServletException if an error occurred
	 * @throws IOException if an error occurred
	 */
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		response.setContentType("text/html");
		PrintWriter out = response.getWriter();
		HttpSession session = request.getSession();
		String name = (String) session.getAttribute("username");
//		if(name == null)
//			out.println(session.getAttribute("username"));
//		else
//			name = "";
		if(name == null)
			name = request.getRemoteAddr();
		String user = name;
		
		
		
		StadiumDAO stadiumDao = new StadiumDAO();
		List<Stadium> stadiums = stadiumDao.findAll();
		
		//用于存储返回的结果
		List result = new ArrayList();
		//先放入用户名   后期可能加入用户的其它信息
		result.add(user);
		
		List rooms = new ArrayList();

		
		for(int i=0; i<stadiums.size(); i++){
			Room room = new Room(200,0,stadiums.get(i).getStadiumLocalName());
			
			//依次得到每个端口，对应的server的人数. 
			room.setNum(StartSocketServlet.socketServerList.get(i).clientList.size());
			
			if(i%2 == 0){
				StartSocketServlet.socketServerList.get(i).type = 'F';
				room.setType('F');
			}else{
				StartSocketServlet.socketServerList.get(i).type = 'D';
				room.setType('D');
			}
				
			
			//设置对应server的端口
			room.setPort(StartSocketServlet.socketServerList.get(i).getPort());
			
			rooms.add(room);
		}
		
		result.add(rooms);
		
		Gson gson = new Gson();
		String str = gson.toJson(result);
		
		System.out.println(str);
		System.out.println("username:" + session.getAttribute("username"));
		
		out.print(str);
		out.flush();
		out.close();
	}

}
